package org.webdb.webapp.interceptors;

import java.io.Closeable;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.picocontainer.Disposable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.webdb.core.ThreadContext;

public class ThreadContextServletFilter implements Filter {

    private static final Logger logger = LoggerFactory
            .getLogger("ThreadContextListener");

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        try {
            chain.doFilter(request, response);
        } finally {
            for (Object object : ThreadContext.get()) {
                try {
                    if (object != null)
                        dispose(object);
                } catch (Exception e) {
                    logger.debug(object.toString() + " not free!", e);
                }
            }
            ThreadContext.clean();
        }
    }

    private void dispose(Object object) throws Exception {
        if (object instanceof Closeable)
            ((Closeable) object).close();

        if (object instanceof Disposable)
            ((Disposable) object).dispose();
    }

    @Override
    public void destroy() {
    }

}
